//
//  HWCommentCircleView.m
//  嗨文
//
//  Created by 响当当 on 6/24/19.
//  Copyright © 2019 dongzheng. All rights reserved.
//

#import "HWCommentCircleView.h"
#import "HWCommentCircleCell.h"
#import <ZLPhotoBrowser/ZLPhotoBrowser.h>
#import "LCAllUserPostPulishItem.h"

@interface HWCommentCircleView()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic, strong)UIView *headView;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)UIView *footView;
@property (nonatomic,strong)UIButton *completeBtn;

@property (nonatomic, strong)NSString *seesionId;
@property (nonatomic, strong)NSMutableArray *btnArr;
@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic,strong)NSMutableArray *datas;
@property (nonatomic,strong)NSMutableArray *imageData;

@property (nonatomic, strong)NSString *title;
@property (nonatomic, strong)NSString *context;

@end

@implementation HWCommentCircleView

- (NSMutableArray *)datas
{
    if (!_datas)
    {
        _datas = [[NSMutableArray alloc]init];
    }
    return _datas;
}

- (NSMutableArray *)imageData
{
    if (!_imageData)
    {
        _imageData = [[NSMutableArray alloc]init];
    }
    return _imageData;
}


- (NSMutableArray *)btnArr
{
    if (!_btnArr)
    {
        _btnArr = [[NSMutableArray alloc]init];
    }
    return _btnArr;
}

- (UIView *)headView
{
    if (!_headView)
    {
        _headView = [[UIView alloc]initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,250*kUIScaleBasePlus)];
        _headView.backgroundColor = [UIColor whiteColor];
    }
    return _headView;
}

- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH,SCREEN_HEIGHT-NAVIBAR_HEIGHT) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = 0;
    }
    return _tableView;
}

- (UIView *)footView
{
    if (!_footView)
    {
        _footView = [[UIView alloc]initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,200*kUIScaleBasePlus)];
        _footView.backgroundColor = [UIColor whiteColor];
    }
    
    return _footView;
}

- (UIButton *)completeBtn
{
    if (!_completeBtn) {
        _completeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        CGFloat height = 44*kUIScaleBasePlus;
        CGFloat width = 141*kUIScaleBasePlus;
        CGFloat y = (60*kUIScaleBasePlus - height)/2;
        _completeBtn.frame = CGRectMake(SCREEN_WIDTH/2 - width/2,y, width, height);
        _completeBtn.titleLabel.font = kSystemFontOfSize(14*kUIScaleBasePlus);
        [_completeBtn setTitle:@"完成" forState:0];
        [_completeBtn setTitleColor:WhiteColor forState:0];
        _completeBtn.backgroundColor = JSAMainColor;
        _completeBtn.layer.masksToBounds = true;
        _completeBtn.layer.cornerRadius = 22*kUIScaleBasePlus;
        
        WeakSelf(self)
        [_completeBtn bk_addEventHandler:^(id sender) {
            
            [weakSelf endEditing:YES];
            if (weakSelf.title.length < 1) {
                [SVProgressHUD showInfoWithStatus:@"请输入标题"];
                DISMISS_SVP(1.0f);
                return;
            }
            if (weakSelf.context.length < 1) {
                [SVProgressHUD showInfoWithStatus:@"请输入发帖内容"];
                DISMISS_SVP(1.0f);
                return;
            }
            [self uploadPulish];
            
        } forControlEvents:UIControlEventTouchUpInside];
    }
    return _completeBtn;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        UICollectionViewFlowLayout *layout =  [[UICollectionViewFlowLayout alloc]init];
        CGFloat headHeight = AdapteAdjust(0.f);
        layout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, headHeight);
        CGFloat footHeight = AdapteAdjust(55.f);
        layout.footerReferenceSize = CGSizeMake(SCREEN_WIDTH, footHeight);
        CGFloat padding = AdapteAdjust(5.f);
        layout.sectionInset = UIEdgeInsetsMake(padding, padding, padding, padding);
        CGFloat itemWidth = 80*kUIScaleBasePlus;
        layout.itemSize = CGSizeMake(itemWidth, itemWidth);
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,200*kUIScaleBasePlus) collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"bottom"];
    }
    return _collectionView;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.seesionId = @"31";
        [self addSubview:self.tableView];
    }
    
    return self;
}

#pragma mark tableview delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  261*kUIScaleBasePlus;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 200*kUIScaleBasePlus;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    HWCommentCircleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentCircleCell"];
    if (!cell)
    {
        cell = [[HWCommentCircleCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"commentCircleCell"];
        cell.selectionStyle = 0;
    }
    
    WeakSelf(self)
    cell.getBackContextBlock = ^(NSString *context) {
        weakSelf.context = context;
    };
    
    cell.getBackTitleBlock = ^(NSString *title) {
        weakSelf.title = title;
    };
    
    return cell;
}


#pragma mark collection delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.datas.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    UICollectionReusableView *bottom = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"bottom" forIndexPath:indexPath];
    [bottom addSubview:self.completeBtn];
    
    return bottom;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    LCAllUserPostPulishItem *cell = [[LCAllUserPostPulishItem alloc]initWithCollectionView:collectionView forCellWithReuseIdentifier:@"LCAllUserPostPulishItem"];
    cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LCAllUserPostPulishItem" forIndexPath:indexPath];
    if (indexPath.row+1 == self.datas.count)
    {
        [cell configData:self.datas[indexPath.row] showDeleteBtn:false];
    }
    else
    {
        [cell configData:self.datas[indexPath.row] showDeleteBtn:true];
    }
    cell.delegate = (id)self;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.datas.count > 9)
    {
        DISMISS_SVP(1.0f);
        [SVProgressHUD showErrorWithStatus:@"最多只能传9张"];
        DISMISS_SVP(1.0f);
        return;
    }
    
    if (indexPath.row == self.datas.count - 1)
    {
        ZLPhotoActionSheet *ac = [[ZLPhotoActionSheet alloc] init];
        //相册参数配置，configuration有默认值，可直接使用并对其属性进行修改
        
        ac.configuration.maxPreviewCount = 10;
        ac.configuration.maxSelectCount = 1;

        //如调用的方法无sender参数，则该参数必传
        ac.sender = (id)[HWUtilties getCurrentVC];
        
        //选择回调
        [ac setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
            //            [_datas removeAllObjects];
            [images enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [self.datas addObject:obj];
                [MyInfoManager postImgsListWithImgList:@[obj] Sucess:^(id  _Nonnull acceptData) {
                    NSDictionary *dic = acceptData[@"data"];
                    [self.imageData addObject:dic[@"fileKey"]];
                } fail:^(NSError * _Nullable error) {
                    
                }];
            }];
            [self.datas exchangeObjectAtIndex:indexPath.row withObjectAtIndex:indexPath.row+1];
            
           
            
            [self.collectionView reloadData];
        }];
        //调用相册
        [ac showPreviewAnimated:YES];
    }else
    {
        
    }
}

#pragma 点击删除按钮
- (void)deleteBtnClickAtIndexCell:(LCAllUserPostPulishItem *)cell
{
    NSInteger index = [self.collectionView indexPathForCell:cell].row;
    [self.datas removeObjectAtIndex:index];
    [self.imageData removeObjectAtIndex:index];
    [self.collectionView reloadData];
}


#pragma mark Method

- (void)creatUI:(NSArray *)arr
{
    CGFloat width = 90*kUIScaleBasePlus;
    CGFloat height = 37*kUIScaleBasePlus;
    
    for (int i=0; i< arr.count; i++)
    {
        UIButton *btn = [HWUtilties creatButtonWithFrame:CGRectMake(37*kUIScaleBasePlus+(width+15*kUIScaleBasePlus)*(i%3),20*kUIScaleBasePlus+(height+15*kUIScaleBasePlus)*(i/3),width,height)
                                            textAligment:NSTextAlignmentCenter
                                                    text:arr[i][@"seriesName"]
                                                textClor:LCHexColor(0x363B43)
                                               buttonBGC:LCHexColor(0xF5F8FB)
                                                textFont:13*kUIScaleBasePlus
                                                  target:self
                                                  method:@selector(boyBookClick:)];
        if (i == 0)
        {
            [btn setBackgroundColor:LCHexColor(0xFFF5F5)];
            [btn setTitleColor:LCHexColor(0xF54337) forState:UIControlStateNormal];
        }
        
        NSNumber *num = IFNULL(arr[i][@"seriesId"], [NSNumber new]);
        btn.tag = [num integerValue];
        [self.btnArr addObject:btn];
        [self.headView addSubview:btn];
    }
    
    
    self.tableView.tableHeaderView = self.headView;
    self.tableView.tableFooterView = self.footView;
    [self.tableView reloadData];
    
    [self.footView addSubview:self.collectionView];
    [self.datas addObject:lc_image(@"tiezi_add")];
    [self.collectionView reloadData];
}


- (void)boyBookClick:(UIButton *)sender
{
    
    [self endEditing:YES];
    self.seesionId = [NSString stringWithFormat:@"%ld",sender.tag];
    
    for (int i=0; i<self.btnArr.count; i++)
    {
        UIButton *btn = self.btnArr[i];
        if (![btn isEqual:sender])
        {
            [btn setBackgroundColor:LCHexColor(0xF5F8FB)];
            [btn setTitleColor:LCHexColor(0x363B43) forState:UIControlStateNormal];
        }
        else
        {
            [btn setBackgroundColor:LCHexColor(0xFFF5F5)];
            [btn setTitleColor:LCHexColor(0xF54337) forState:UIControlStateNormal];
        }
    }
    
}

- (void)uploadPulish
{
    //防止多次点击
    self.completeBtn.userInteractionEnabled = false;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.completeBtn.userInteractionEnabled = true;
    });
    
    [SVProgressHUD showWithStatus:nil];
    if (self.imageData.count > 0)
    {
        
        NSString *imageList = @"";
        for (int i=0; i<self.imageData.count; i++)
        {
            if (i<self.imageData.count-1)
            {
                imageList = [imageList stringByAppendingString:[NSString stringWithFormat:@"\"%@\",",self.imageData[i]]];
            }
            else
            {
                imageList = [imageList stringByAppendingString:[NSString stringWithFormat:@"\"%@\"",self.imageData[i]]];
            }
        }
        
        NSString *str = [NSString stringWithFormat:@"[%@]",imageList];
        
        NSDictionary *prarmers = @{
                                   @"access_token" : current_User.token,
                                   @"seriesId" : self.seesionId,
                                   @"title" : self.title,
                                   @"content" : self.context,
                                   @"imageList": str
                                   };
        
        [MyInfoManager addCommentComplete:prarmers sucess:^(id  _Nonnull acceptData)
         {
             DISMISS_SVP(1.0f);
             [SVProgressHUD showErrorWithStatus:@"发表成功"];
             DISMISS_SVP(1.0f);
             [[HWUtilties getCurrentVC].navigationController popViewControllerAnimated:YES];
         } fail:^(NSError * _Nullable error) {
             DISMISS_SVP(1.0f);
             [SVProgressHUD showErrorWithStatus:@"发表失败"];
             DISMISS_SVP(1.0f);
         }];
    }
    else
    {
        DISMISS_SVP(1.0f);
        [SVProgressHUD showErrorWithStatus:@"请添加照片"];
        DISMISS_SVP(1.0f);
    }
}

@end
